import { HttpException, Injectable } from '@nestjs/common';
import { EverydayData } from '@/module/everyday-data/entities/everyday-datum.entity';
import { DeepPartial, Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { TypeOrmCrudService } from '@dataui/crud-typeorm';
import { TestingMachine } from '@/testing-machine/entities/testing-machine.entity';
import { CreateManyDto, CrudRequest } from '@dataui/crud';
import { CreateEverydayDatumDto } from '@/module/everyday-data/dto/create-everyday-datum.dto';

async function checkExist(testId: number, testDate: Date) {
  const one = await this.extracted(testId, testDate as Date);
  if (one) {
    throw new HttpException(
      one.testingMachine.machineName + '的' + testDate + '记录已存在',
      400,
    );
  }
}

@Injectable()
export class EverydayDataService extends TypeOrmCrudService<EverydayData> {
  constructor(
    @InjectRepository(EverydayData)
    private readonly everydayDataRepository: Repository<EverydayData>,
    @InjectRepository(TestingMachine)
    private readonly testingMachineRepo: Repository<TestingMachine>,
  ) {
    super(everydayDataRepository);
  }

  async createMany(
    req: CrudRequest,
    dto: CreateManyDto<DeepPartial<EverydayData>>,
  ): Promise<EverydayData[]> {
    for (let i = 0; i < dto.bulk.length; i++) {
      // 验证数据库中,是否存在testingMachineId和uploadDate都一样的记录,如果存在返回对应的everydayData的testMachine的machineName
      const testId = dto.bulk[i].testingMachine.id;
      const testDate = dto.bulk[i].uploadDate;
      await checkExist.call(this, testId, testDate);
    }
    return super.createMany(req, dto);
  }

  async extracted(testId: number, testDate: Date) {
    const result = await super.findOne({
      where: {
        testingMachine: {
          id: testId,
        },
        uploadDate: testDate as Date,
      },
      relations: ['testingMachine', 'fileUploads'],
    });
    return result;
  }

  async createOneByEverydayData(
    req: CrudRequest,
    dto: DeepPartial<CreateEverydayDatumDto>,
  ) {
    const everydayData = await this.everydayDataRepository.create(dto);

    everydayData.testingMachine = await this.testingMachineRepo.findOne({
      where: {
        id: dto.testingMachineId,
      },
    });
    if (!everydayData.testingMachine) {
      throw new Error('testingMachine not found');
    }
    await checkExist.call(
      this,
      everydayData.testingMachine.id,
      everydayData.uploadDate,
    );
    console.log(req, dto);
    await this.everydayDataRepository.save(everydayData);
    return;
  }
}
